'use client'

import request from '@/utils/frontend/request'
import { SearchOutlined } from '@ant-design/icons'
import { Button, Input, Modal, Table, type TableProps, message } from 'antd'
import { useEffect, useState, useRef } from 'react'
import { formatGender } from '@/utils/frontend/format'

interface FriendRequestItem {
	id: number
	sender: {
		id: number
		username: string
		nickname: string
		gender: 'male' | 'female' | 'unknown'
		avatar: string | null
	}
	receiver: {
		id: number
		username: string
		nickname: string
		gender: 'male' | 'female' | 'unknown'
		avatar: string | null
	}
	status: 'pending' | 'accepted' | 'rejected'
	createdAt: string
}

interface PaginationState {
	current: number
	pageSize: number
	total: number
}

// 修改列定义，根据请求类型显示不同的用户信息
const getColumns = (
	type: 'received' | 'sent',
	onAccept: (id: number) => void,
	onReject: (id: number) => void
): TableProps<FriendRequestItem>['columns'] => [
	{
		title: '用户名',
		dataIndex: [type === 'received' ? 'sender' : 'receiver', 'username'],
		key: 'username',
	},
	{
		title: '昵称',
		dataIndex: [type === 'received' ? 'sender' : 'receiver', 'nickname'],
		key: 'nickname',
	},
	{
		title: '性别',
		dataIndex: [type === 'received' ? 'sender' : 'receiver', 'gender'],
		key: 'gender',
		render: (gender: 'male' | 'female' | 'unknown') => formatGender(gender),
	},
	{
		title: '申请时间',
		dataIndex: 'createdAt',
		key: 'createdAt',
		render: (date: string) => new Date(date).toLocaleString(),
	},
	{
		title: '状态',
		dataIndex: 'status',
		key: 'status',
		render: (status: string) => {
			const statusMap = {
				pending: '待处理',
				accepted: '已接受',
				rejected: '已拒绝',
			}
			return statusMap[status as keyof typeof statusMap]
		},
	},
	{
		title: '操作',
		key: 'action',
		render: (_, record) => {
			if (record.status === 'pending' && type === 'received') {
				return (
					<div className="space-x-2">
						<Button type="primary" size="small" onClick={() => onAccept(record.id)}>
							接受
						</Button>
						<Button danger size="small" onClick={() => onReject(record.id)}>
							拒绝
						</Button>
					</div>
				)
			}
			return null
		},
	},
]

export default function FriendRequest() {
	const [messageApi, contextHolder] = message.useMessage()
	const isFirstRender = useRef(true)
	const [pagination, setPagination] = useState<PaginationState>({
		current: 1,
		pageSize: 10,
		total: 0,
	})
	const [searchText, setSearchText] = useState('')
	const [loading, setLoading] = useState(false)
	const [requestList, setRequestList] = useState<FriendRequestItem[]>([])
	const [requestType, setRequestType] = useState<'received' | 'sent'>('received')

	// 获取好友请求列表
	const fetchRequestList = async (
		page = pagination.current,
		pageSize = pagination.pageSize,
		keyword = searchText,
		type = requestType
	) => {
		try {
			setLoading(true)
			const params = new URLSearchParams({
				page: String(page),
				pageSize: String(pageSize),
				keyword,
				type,
			})

			const { data } = (await request.get(`/friend/request?${params}`)) as ApiResponse
			setRequestList(data.list)
			setPagination((prev) => ({
				...prev,
				current: data.pagination.current,
				total: data.pagination.total,
			}))
		} catch (error) {
			messageApi.error('获取好友请求列表失败，请稍后重试')
		} finally {
			setLoading(false)
		}
	}

	// 首次加载获取好友请求列表
	useEffect(() => {
		if (isFirstRender.current) {
			console.log('created')
			fetchRequestList()
			isFirstRender.current = false
			return
		}
	}, [])

	// 处理分页变化
	const handleTableChange: TableProps<FriendRequestItem>['onChange'] = (
		pagination,
		filters,
		sorter
	) => {
		const { current, pageSize } = pagination
		fetchRequestList(current, pageSize)
	}

	// 处理搜索
	const handleSearch = (value: string) => {
		setSearchText(value)
		fetchRequestList(1, pagination.pageSize, value)
	}

	// 处理搜索框变化
	const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
		setSearchText(e.target.value)
	}

	// 处理接受好友请求
	const handleAccept = async (requestId: number) => {
		try {
			const { success, message } = (await request.post('/friend/request/operation', {
				requestId,
				operation: 'accept',
			})) as ApiResponse

			if (success) {
				messageApi.success(message)
				fetchRequestList() // 刷新列表
			} else {
				messageApi.error(message)
			}
		} catch (error) {
			messageApi.error('接受好友请求失败，请重试')
		}
	}

	// 处理拒绝好友请求
	const handleReject = async (requestId: number) => {
		try {
			const { success, message } = (await request.post('/friend/request/operation', {
				requestId,
				operation: 'reject',
			})) as ApiResponse

			if (success) {
				messageApi.success(message)
				fetchRequestList() // 刷新列表
			} else {
				messageApi.error(message)
			}
		} catch (error) {
			messageApi.error('拒绝好友请求失败，请重试')
		}
	}

	// 添加切换请求类型的处理函数
	const handleTypeChange = (type: 'received' | 'sent') => {
		setRequestType(type)
		setSearchText('')
		setPagination((prev) => ({ ...prev, current: 1 }))
		fetchRequestList(1, pagination.pageSize, '', type)
	}

	return (
		<div className="space-y-4">
			{contextHolder}
			{/* 顶部操作区域 */}
			<div className="flex justify-between items-center">
				<div className="w-80">
					<Input.Search
						placeholder="搜索好友请求..."
						allowClear
						size="large"
						enterButton={<SearchOutlined />}
						onSearch={handleSearch}
						onChange={handleSearchChange}
						value={searchText}
					/>
				</div>
				<div className="space-x-2">
					<Button
						type={requestType === 'received' ? 'primary' : 'default'}
						onClick={() => handleTypeChange('received')}
					>
						我接收的
					</Button>
					<Button
						type={requestType === 'sent' ? 'primary' : 'default'}
						onClick={() => handleTypeChange('sent')}
					>
						我发起的
					</Button>
				</div>
			</div>

			{/* 好友请求列表 */}
			<Table
				columns={getColumns(requestType, handleAccept, handleReject)}
				dataSource={requestList}
				rowKey="id"
				loading={loading}
				pagination={{
					...pagination,
					showSizeChanger: true,
					showQuickJumper: true,
					showTotal: (total) => `共 ${total} 条记录`,
				}}
				onChange={handleTableChange}
			/>
		</div>
	)
}
